# Create your views here.
import re
import datetime
import time

from django.shortcuts import render
from django.core.exceptions import ObjectDoesNotExist

from loginocb.forms import HyperiumsForm
from loginocb.utils import get_message_from_url, authenticate_from_hapikey
from constants import HYPERIUMS_HAPI_ROOT, DESTROYERS, BOMBERS, SCOUTS, CRUISERS, ARMIES
from planet.models import Planet, PlanetInfo
from player.models import OCBPlayer, Player
from fleet.models import StaticFleet, MovingFleet

def index(request):
    
    return render(request, 'misc/index.html')


def updatedata(request):
    
    if request.method == "GET" :
        form = HyperiumsForm()
        return render(request,'loginocb/updatedata.html',{'form':form})
    else :
        form = HyperiumsForm(data=request.POST)
        if form.is_valid():
            login_info = authenticate_from_hapikey(request.POST['login'],request.POST['authentication_key'])
            if 'error' in login_info.keys() :
                return render(request,'loginocb/updatedata.html',{'form':HyperiumsForm(),
                                                                              'error':login_info['error']})
            else :
                url = "%sgameid=%s&playerid=%s&authkey=%s&"%(HYPERIUMS_HAPI_ROOT,login_info['gameid'],login_info['playerid'],login_info['authkey'])
                
                """
                    Update informations on user planets
                    Foreach planet we get the PlanetInfo
                    We get also PlanetInfo and check if it is still owned by user
                """
                
                
                info_request = "request=getplanetinfo&planet=*&data=general"
                message = get_message_from_url(url+info_request)
                planets = re.split("planet\d+\=",message)
                planets.pop(0)
                
                qs_planets = PlanetInfo.objects.filter(planet_owner = OCBPlayer.objects.get(user=request.user))
                for pl in planets:
                    try :
                        planet_name = pl.split('&')[0]
                        ocb_planet = PlanetInfo.objects.get(planet=Planet.objects.get(name=planet_name))
                        player = OCBPlayer.objects.get(user=request.user)
                        if ocb_planet.planet_owner != player:
                            ocb_planet.planet_owner = player
                        ocb_planet.last_update_date = datetime.datetime.now()-datetime.timedelta(hours=2)
                        ocb_planet.save()
                        qs_planets = qs_planets.exclude(planet = ocb_planet.planet)
                    except ObjectDoesNotExist:
                        pass
                    
                for planet in qs_planets:
                    planet.planet_owner = None
                    planet.energy = None
                    planet.max_energy = None
                    planet.stasis = 3
                    planet.save()
                time.sleep(1)
                
                """
                    updating fleets informations
                    for owned planets
                """
                info_request = "request=getfleetsinfo&planet=*&data=own_planets"
                message = get_message_from_url(url+info_request)
                all_fleets = re.split("planet\d+\=",message)
                all_fleets.pop(0)
                n = 0
                for planet_fleet in all_fleets:
                    #print planet_fleet
                    planet_infos = planet_fleet.split('&')
                    planet_object = Planet.objects.get(name=planet_infos[0])
                    
                    current_fleets = StaticFleet.objects.filter(planet=planet_object)
                    for fleet in current_fleets:
                        fleet.delete()

                    planet_infos.pop(0)
                    planet_infos.pop(-1)
                    dict_infos = dict(pl.split('=') for pl in planet_infos)
                    try :
                        ocb_planet_object = PlanetInfo.objects.get(planet=planet_object)
                        ocb_planet_object.energy = int(dict_infos['nrj%s'%n])
                        ocb_planet_object.max_energy = int(dict_infos['nrjmax%s'%n])
                        if int(dict_infos['stasis%s'%n]) == 1 :
                            ocb_planet_object.stasis = 1
                        elif int(dict_infos['stasis%s'%n]) == 0 :
                            ocb_planet_object.stasis = 2
                        else :
                            ocb_planet_object.stasis = 3
                        ocb_planet_object.save()
                    except ObjectDoesNotExist:
                        n += 1
                        continue
                    f=0
                    while 1 :
                        if 'fleetid%s.%s'%(n,f) in dict_infos.keys():
                            fleet = StaticFleet(
                                    hyperiums_id = dict_infos['fleetid%s.%s'%(n,f)],
                                    planet = planet_object,
                                    race = int(dict_infos['frace%s.%s'%(n,f)]),
                                    defending = bool(int(dict_infos['defend%s.%s'%(n,f)])),
                                    last_update_date = datetime.datetime.now()-datetime.timedelta(hours=2)
                                        )
                            if 'owner%s.%s'%(n,f) in dict_infos.keys() and dict_infos['owner%s.%s'%(n,f)] != '?' and dict_infos['owner%s.%s'%(n,f)] != 'Hyperiums' :
                                fleet.owner = Player.objects.get(nickname=dict_infos['owner%s.%s'%(n,f)])
                            if 'scou%s.%s'%(n,f) in dict_infos.keys() :
                                fleet.amount_fleet = int(dict_infos['scou%s.%s'%(n,f)])*SCOUTS[fleet.race] + \
                                                     int(dict_infos['crui%s.%s'%(n,f)])*CRUISERS[fleet.race] + \
                                                     int(dict_infos['bomb%s.%s'%(n,f)])*BOMBERS[fleet.race] + \
                                                     int(dict_infos['dest%s.%s'%(n,f)])*DESTROYERS[fleet.race]
                                if 'bombing%s.%s' in dict_infos.keys():
                                    fleet.bombing = bool(int(dict_infos['bombing%s.%s'%(n,f)]))
                            if 'carmies%s.%s'%(n,f) in dict_infos.keys() and dict_infos['carmies%s.%s'%(n,f)] != '?':
                                fleet.amount_GA = int(dict_infos['carmies%s.%s'%(n,f)])*ARMIES[fleet.race]
                            elif 'garmies%s.%s'%(n,f) in dict_infos.keys() and dict_infos['garmies%s.%s'%(n,f)] != '?':
                                fleet.amount_GA = int(dict_infos['garmies%s.%s'%(n,f)])*ARMIES[fleet.race]
                            fleet.save()  
                            f += 1 
                        else :
                            break

                    n += 1
                
                """
                    updating fleets on foreign planets
                """
                
                info_request = "request=getfleetsinfo&planet=*&data=foreign_planets"
                message = get_message_from_url(url+info_request)
                all_fleets = re.split("planet\d+\=",message)
                all_fleets.pop(0)
                n = 0
                for planet_fleet in all_fleets:

                    planet_infos = planet_fleet.split('&')
                    planet_object = Planet.objects.get(name=planet_infos[0])
                    
                    current_fleets = StaticFleet.objects.filter(planet=planet_object)
                    for fleet in current_fleets:
                        fleet.delete()

                    planet_infos.pop(0)
                    if planet_infos[-1] == '':
                        planet_infos.pop(-1)
                    dict_infos = dict(pl.split('=') for pl in planet_infos)
                    try :
                        ocb_planet_object = PlanetInfo.objects.get(planet=planet_object)
                        if 'nrj%s' in dict_infos.keys():
                            ocb_planet_object.energy = int(dict_infos['nrj%s'%n])
                            ocb_planet_object.max_energy = int(dict_infos['nrjmax%s'%n])
                        if 'isneutral%s'%n in dict_infos.keys() :
                            ocb_planet_object.is_neutral = int(dict_infos['isneutral%s'%n])
                        ocb_planet_object.stasis = bool(int(dict_infos['stasis%s'%n]))
                        ocb_planet_object.last_update_date = datetime.datetime.now()
                        ocb_planet_object.save()
                    except ObjectDoesNotExist:
                        n += 1
                        continue
                    f=0
                    while 1 :
                        if 'fleetid%s.%s'%(n,f) in dict_infos.keys():
                            fleet = StaticFleet(
                                    hyperiums_id = dict_infos['fleetid%s.%s'%(n,f)],
                                    planet = planet_object,
                                    race = int(dict_infos['frace%s.%s'%(n,f)]),
                                    defending = bool(int(dict_infos['defend%s.%s'%(n,f)])),
                                    last_update_date = datetime.datetime.now()-datetime.timedelta(hours=2)
                                        )
                            if 'bombing%s.%s'%(n,f) in dict_infos.keys():
                                        fleet.bombing = bool(int(dict_infos['bombing%s.%s'%(n,f)]))
                            if 'owner%s.%s'%(n,f) in dict_infos.keys() and dict_infos['owner%s.%s'%(n,f)] != '?' :
                                fleet.owner = Player.objects.get(nickname=dict_infos['owner%s.%s'%(n,f)])
                            if fleet.defending and OCBPlayer.objects.filter(player=fleet.owner) :
                                ocb_planet_object.planet_survey.add(fleet.owner.ocbplayer_set.all()[0])
                            if 'scou%s.%s'%(n,f) in dict_infos.keys() :
                                fleet.amount_fleet = int(dict_infos['scou%s.%s'%(n,f)])*SCOUTS[fleet.race] + \
                                                     int(dict_infos['crui%s.%s'%(n,f)])*CRUISERS[fleet.race] + \
                                                     int(dict_infos['bomb%s.%s'%(n,f)])*BOMBERS[fleet.race] + \
                                                     int(dict_infos['dest%s.%s'%(n,f)])*DESTROYERS[fleet.race]
                            if 'carmies%s.%s'%(n,f) in dict_infos.keys() and dict_infos['carmies%s.%s'%(n,f)] != '?' :
                                fleet.amount_GA = int(dict_infos['carmies%s.%s'%(n,f)])*ARMIES[fleet.race]
                            elif 'garmies%s.%s'%(n,f) in dict_infos.keys() and dict_infos['garmies%s.%s'%(n,f)] != '?' :
                                fleet.amount_GA = int(dict_infos['garmies%s.%s'%(n,f)])*ARMIES[fleet.race]
                            fleet.save()
                            f += 1 
                        else :
                            break

                    n += 1
                #pour chaque flotte il faut regarder si elle est toujours en mouvement (hyperiums_id), et updater si elle existe encore
                info_request = "request=getmovingfleets"
                message = get_message_from_url(url+info_request)
                #print message
                all_fleets = re.split("fleetid\d+\=",message)
                all_fleets.pop(0)
                n=0
                for moving_fleet in all_fleets:
                    #print moving_fleet
                    fleet_info = moving_fleet.split('&')
                    fleet_id = int(fleet_info[0])
                    fleet_info.pop(0)
                    if fleet_info[-1] == '':
                        fleet_info.pop(-1)
                    dict_fleet_info = dict(pl.split('=') for pl in fleet_info)
                    #print dict_fleet_info
                    real_time = datetime.datetime.now() + datetime.timedelta(hours=(int(dict_fleet_info['delay%s'%n])+int(dict_fleet_info['dist%s'%n]))) - datetime.timedelta(hours=2, minutes=50)
                    arrival_time = datetime.datetime(year=real_time.year,
                                                     month=real_time.month,
                                                     day=real_time.day,
                                                     hour=real_time.hour,
                                                     minute=50
                                                     )

                    moving_fleet,created = MovingFleet.objects.get_or_create(hyperiums_id=fleet_id,
                                                             defaults={
                                                                    'planet_destination':Planet.objects.get(name=dict_fleet_info['to%s'%n]),
                                                                    'arrival_time':arrival_time,
                                                                    'race':int(dict_fleet_info['race%s'%n]),
                                                                    'owner':request.user.ocbplayer_set.all()[0].player,
                                                                    'defending':bool(int(dict_fleet_info['defend%s'%n])),
                                                                    'bombing':bool(int(dict_fleet_info['bombing%s'%n])),
                                                                    'last_update_date':datetime.datetime.now()-datetime.timedelta(hours=2)                   
                                                                        })
                    if not created :
                        moving_fleet.planet_destination=Planet.objects.get(name=dict_fleet_info['to%s'%n])
                        moving_fleet.arrival_time=arrival_time
                        moving_fleet.defending=bool(int(dict_fleet_info['defend%s'%n]))
                        moving_fleet.bombing=bool(int(dict_fleet_info['bombing%s'%n]))
                        moving_fleet.last_update_date=datetime.datetime.now()-datetime.timedelta(hours=2)
                    moving_fleet.amount_fleet = int(dict_fleet_info['nbscou%s'%n])*SCOUTS[moving_fleet.race] + \
                                                     int(dict_fleet_info['nbcrui%s'%n])*CRUISERS[moving_fleet.race] + \
                                                     int(dict_fleet_info['nbbomb%s'%n])*BOMBERS[moving_fleet.race] + \
                                                     int(dict_fleet_info['nbdest%s'%n])*DESTROYERS[moving_fleet.race]
                    moving_fleet.amount_GA = int(dict_fleet_info['nbarm%s'%n])*ARMIES[moving_fleet.race]
                    moving_fleet.save()
                    n += 1
                return render(request,'loginocb/updatedata.html',{'form':HyperiumsForm()})
